/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable max-len */
import { message } from 'antd';
import {
  getStationList,
  getZyStationList,
  getOthersStationList,
  deleteStation,
  saveStation,
  saveStationForPartner,
  deleteStationForPartner,
} from '../services/api';

export default {
  namespace: 'station',
  state: {
    list: null,
    company_info: null,
  },

  effects: {
    *getStationList({ payload, __dva_resolve }, { call, put, select }) {
      const { options = {} } = yield select(_ => _.setting);
      const { key } = options;
      const {
        currentUser: { shop_id, phone },
      } = yield select(_ => _.user);
      const searchApi = {
        yz: getStationList,
        post: getZyStationList,
        yjy: getOthersStationList,
      };

      const response = yield call(searchApi[key], { shop_id, phone, ...payload }); // 中邮获取站点需要单独的接口
      if (!response) return;
      const { code, data, msg } = response;
      if (code == 0 && data) {
        const { result, company_info } = data;

        const stationData = {
          list: result,
        };
        // 兼容没有主站点的情况
        if (company_info) {
          stationData.company_info = { ...company_info[0], site_id: -1 };
          stationData.selectedKeys = [company_info[0].brand_code]; // 初始设置选中的站点
          stationData.currentStation = { ...company_info[0], site_id: -1 }; // 初始时，设置当前站点信息，主站点site_id为 -1
        } else {
          const [firstSite = {}] = result || 0;
          stationData.selectedKeys = [firstSite.site_id];
          stationData.currentStation = firstSite;
        }

        yield put({
          type: 'updateState',
          payload: stationData,
        });
        __dva_resolve(stationData);
      } else {
        message.error(msg);
      }
    },
    *saveStation({ payload, __dva_resolve, __dva_reject }, { call, put, select }) {
      const { options = {} } = yield select(_ => _.setting);
      const { key } = options;
      const saveApi = key === 'post' || key === 'yz' ? saveStation : saveStationForPartner;

      const response = yield call(saveApi, payload);
      if (!response) return;
      const { code, data, msg } = response;
      if (code == 0) {
        let { list } = yield select(_ => _.station);
        list = list || [];
        // 更新station
        const { site_id, name: site_name, phone: site_phone, charge: site_charge } = payload;
        if (site_id) {
          const len = list.length;
          for (let i = 0; i < len; i += 1) {
            const currentStation = list[i];
            const stationsCode = currentStation.site_id;
            if (stationsCode === site_id) {
              list[i] = {
                ...currentStation,
                ...{
                  site_name,
                  site_charge,
                  site_phone,
                },
              };
              break;
            }
          }
          message.success('已修改');
        } else {
          list.push({
            ...data,
          });
          message.success('已添加');
        }
        yield put({
          type: 'updateState',
          payload: {
            list,
            code,
            site_id: site_id || data.site_id,
          },
        });
        __dva_resolve(response);
      } else {
        message.error(msg);
        __dva_reject(response);
      }
    },
    *deleteStation({ payload }, { call, put, select }) {
      const { options = {} } = yield select(_ => _.setting);
      const { key } = options;
      const deleteApi = key === 'post' || key === 'yz' ? deleteStation : deleteStationForPartner;

      const response = yield call(deleteApi, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        const { list } = yield select(_ => _.station);
        for (let i = 0, len = list.length; i < len; i += 1) {
          const payloadId = payload.site_id;
          if (list[i].site_id == payloadId) {
            list.splice(i, 1);
            break;
          }
        }
        yield put({
          type: 'updateState',
          payload: {
            list,
          },
        });
        message.success('已删除');
      } else {
        message.error(msg);
      }
    },
  },

  reducers: {
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
